import {
    initView,
    createRecord,
    showPromptDialog,
    hidePromptDialog,
    showLoadingDialog,
    hideLoadingDialog
} from '../views/tradeDetailView.js';

import {} from '../base/observer.js';
var cw = require("../components/winLocation.js");
import {
    errorDialog
} from '../components/errorDialog.js';
import {
    Logout
} from '../components/logout.js';
var logoutObject;


var token, loginName, openid, loginType, orderId, goodsAmount;
var errorObject;
var recordScroll;
var pageNum = 1,
    pageSize = 20;
var $wrapper;

$(document).on("pageinit", "#tradeDetail_page", controllerInit);

// 交易查询控制器初始化
function controllerInit() {
    cw.checkBrowser();
    initValue();
    initView();
    subscribeRecordData();
    bindEvent();
}


// 取交易记录数据
function subscribeRecordData() {
    showLoadingDialog();
    var srParameters = {
        "token": token,
        "loginName": loginName,
        "bizLicNo": loginName,
        "openid": openid,
        "loginType": loginType,
        "pageNum": pageNum,
        "pageSize": pageSize
    };

    $.post(TransactionSevlet_URL, srParameters, TRback);


}

// 交易记录回调函数
function TRback(trData) {
    hideLoadingDialog();
    if (trData.login_response) {
        haslogin(trData);
        return;
    }
    if (trData.tltdtrans_response && trData.tltdtrans_response.trans_info_arrays && trData.tltdtrans_response.trans_info_arrays.trans_info) {
        var $cells = $("#record_cells");
        var transInfos = trData.tltdtrans_response.trans_info_arrays.trans_info
        if (transInfos.length == 0) {
            errorObject.showErroDialog("没有交易记录");
        } else {
            if (transInfos.length == undefined) { // 只有一条记录时返回的是对象不是数组处理
                var oneTransInfos = [];
                oneTransInfos.push(transInfos);
                transInfos = oneTransInfos;
            }
            createRecord(transInfos, $cells);
        }
        if (!transInfos || transInfos.length < 20) {
            $wrapper.find('#pullup').html("没有更多记录了");
        }

    } else if (trData.tltdtrans_response && trData.tltdtrans_response.resp_msg) {
        errorObject.showErroDialog(trData.tltdtrans_response.resp_msg);
    } else {
        errorObject.showErroDialog("查询交易记录失败");
    }


}

// 退货请求
function returnGoods() {
    var rgParameters = {
        "token": token,
        "loginName": loginName,
        "bizLicNo": loginName,
        "openid": openid,
        "loginType": loginType,
        "orderId": orderId,
        "goodsAmount": goodsAmount
    };
    $.post(MerRefunds_URL, rgParameters, rgback);
}

//  退货回调函数
function rgback(rgdata) {
    if (rgdata.login_response) {
        haslogin(rgdata);
        return;
    }
    console.dir(rgdata);
    if (rgdata.lft_orderinfo_response && rgdata.lft_orderinfo_response.resp_code == "0000") {
        errorObject.showErroDialog("退货申请成功");
    } else {
        errorObject.showErroDialog("退货失败");
    }
    subscribeRecordData();
}

// 点击订单详情列表到订单详情页
function linkOrderDetail(e) {
    var trans_seq;
    if ($(e.target).attr("data-goods_Amount")) {
        if ($(e.target).hasClass("weui-btn_plain-disabled")) {
            return;
        } else {
            goodsAmount = $(e.target).attr("data-goods_Amount");
            orderId = $(e.target).attr("data-order_id");
            showPromptDialog();
        }
    } else if ($(e.target).attr("data-trans_seq")) {
        trans_seq = $(e.target).attr("data-trans_seq");
    } else {
        var theParnet = $(e.target).parents("[data-trans_seq]");
        if (theParnet[0]) {
            trans_seq = theParnet.attr("data-trans_seq");
        }
    }
    if (trans_seq) {
        location.href = "./orderDetail.html?trans_seq=" + trans_seq;
    }
}

// 判断是否有效登入
function haslogin(msg) {
    if (msg.login_response) {
        errorObject.showErroDialog("该账户已在别的地方登录,请重新登入");
        setTimeout(function() {
            location.href = LoginInit_URL;
        }, 3000);
    }
}

// 绑定事件
function bindEvent() {
    $("#record_cells").on("click", linkOrderDetail);
    $("#return-yes").on("touchend", function() {
        hidePromptDialog();
        returnGoods();
    });
    initIscroll();
}


/*-----------------------------------
滚动模块 */

function initIscroll() {
    var pullText = {
        "pulldownRefresh": "下拉刷新...",
        "pullupLoadingMore": '上拉加载更多...',
        "releaseToRefresh": '松手开始刷新...',
        "releaseToLoading": '松手开始加载...',
        "loading": '加载中...'
    };
    setTimeout(function() {
        recordScroll = new IScroll('#iScroll-box');

        //滚动结束之后触发的事件
        recordScroll.on('scrollEnd', function() {
            console.log("dfksjd");
            var $pulldown = $wrapper.find('#pulldown'),
                $pullup = $wrapper.find('#pullup');

            if ($pulldown.length > 0 && this.y >= 0) {
                $pulldown.removeClass().addClass('loading');
                $pulldown.find('#pulldown-label').html(pullText.releaseToRefresh);
                if (typeof pullDownAction === 'function') {
                    pullDownAction.call(recordScroll);
                }
            } else if ($pulldown.length > 0 && this.y < -5 && this.y > this.maxScrollY + 5) {
                $pullup.find('#pullup-label').html(pullText.pullupLoadingMore);
            } else if ($pullup.length > 0 && this.y <= this.maxScrollY) {
                $pullup.removeClass().addClass('loading');
                $pullup.find('#pullup-label').html(pullText.loading);
                if (typeof pullUpAction === 'function' && $pullup.parent().length > 0) {
                    pullUpAction.call(recordScroll);
                }
            }
        });

    }, 800);
}
/**
 * 下拉刷新
 */
function pullDownAction() {
    console.log("pullDownAction");
    $cells.empty();
    pageNum = 1;
    subscribeRecordData();

}

/*上拉加载更多*/
function pullUpAction() {
    pageNum++;
    subscribeRecordData();
}

/* 滚动模块
-------------------------------------------*/


// 初始化变量
function initValue() {
    errorObject = new errorDialog();
    getSessionStorage();
    logoutObject = new Logout();
    $wrapper = $('#iScroll-box');
}



// 取本地存储essionStorage
function getSessionStorage() {
    token = sessionStorage.getItem("tltd_token");
    loginName = sessionStorage.getItem("tltd_loginName");
    openid = sessionStorage.getItem("tltd_openid");
    loginType = sessionStorage.getItem("tltd_loginType");
    console.log(token, loginName, openid, loginType);
}